import starClass from '@/components/rating/style'
import Love from '@/components/love'
import AJAX from '@/utils/ajax'

class Popup {
  constructor(item, time) {
    this.show(item, time)
  }

  show(item, time) {
    let timer = null
    const pop = $('.d-pop')
    const that = this
    item.hover(
      function() {
        pop.html('')
        const y = $(this).offset().top
        const id = $(this).data('id')
        const w = $(this).width()
        let x = $(this).offset().left
        let s = ''
        if (id) {
          if (1200 - 1.2 * x < w) {
            x = x - 360
            s = 'style="margin-right:15px;"'
          } else {
            x = x + w - 5
          }
          timer = setTimeout(function() {
            pop.css({ top: y, left: x, display: 'block' })
            AJAX({ url: 'pop', data: { id } }).then(res => {
              console.log(res)
              const { gold, url, name, year, time, list_url, list_name, area, mcid, director, actor, cid, content } = res.data
              const starNum = starClass((gold * 10) / 2)
              const goldH = parseFloat(gold) ? `<p class="rank"><span id="d-star" class="${starNum}"></span><strong>${parseFloat(gold)}</strong></p>` : ''
              const d = that.toH(director, 2)
              const a = that.toH(actor, 1)
              const html = `<div class="d-box" ${s}><div class="d-popinfo"><h3><a href="${url}">${name}(${year})</a></h3>${goldH}<p class="meta mt10 clearfix"><span class="green">${time}</span><a href="${list_url}">${list_name}</a>${area}${mcid}${d}${a}</p><p class="collect-area"><a class="love" data-type="love" data-id="${id}" data-cid="${cid}"><i class="iconfont">&#xe633;</i>收藏</a><a class="remind" data-type="remind" data-id="${id}" data-cid="${cid}"><i class="iconfont">&#xe60c;</i>订阅</a></p></div><p class="comment">${content}</p></div>`
              pop.html(html)
              new Love({ id, sid: 1 })
            })
          }, time)
        }
      },
      function() {
        clearTimeout(timer)
        pop.hide()
      }
    )
    pop.hover(
      function() {
        $(this).show()
      },
      function() {
        $(this).hide()
      }
    )
  }

  toH(data = [], type) {
    let h = ''
    const d = data.splice(0, type === 1 ? 3 : 1)
    for (let i = 0; i < d.length; i++) {
      if (d[i].id) {
        h += `<a href="/star/${d[i].id}/">${d[i].title}</a>`
      }
      h += `<a href="/search/${encodeURIComponent(d[i].title)}.html">${d[i].title}</a>`
    }
    return h
  }
}

export default Popup
